/*
 * Powered By [pkuWx]
 * Web Site: http://www.wuxi.ss.pku.edu.cn
 * Since 2015 - 2015
 */


package cn.edu.pku.wxlib.user.controller;

import java.text.SimpleDateFormat;
import java.util.Date;

import javacommon.base.BaseRestSpringController;
import javacommon.page.Page;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import cn.edu.pku.wxlib.common.authority.Login;
import cn.edu.pku.wxlib.student.model.Student;
import cn.edu.pku.wxlib.student.service.StudentManager;
import cn.edu.pku.wxlib.teacher.model.Teacher;
import cn.edu.pku.wxlib.teacher.service.TeacherManager;
import cn.edu.pku.wxlib.user.model.User;
import cn.edu.pku.wxlib.user.service.UserManager;
import cn.edu.pku.wxlib.user.vo.query.UserQuery;
import cn.edu.pku.wxlib.vo.response.StudentUser;
import cn.edu.pku.wxlib.vo.response.TeacherUser;
import cn.org.rapid_framework.web.scope.Flash;

/**
 * @version 1.0
 * @since 1.0
 */

@Controller
@RequestMapping("/user")
public class UserController extends BaseRestSpringController<User,java.lang.Integer>{
		
	private final String LIST_ACTION = "redirect:/user";
	
	private UserManager userManager;
	private TeacherManager teacherManager;
	private StudentManager studentManager;

	public void setStudentManager(StudentManager studentManager) {
		this.studentManager = studentManager;
	}

	public void setTeacherManager(TeacherManager teacherManager) {
		this.teacherManager = teacherManager;
	}

	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}

	@InitBinder  
	public void initBinder(WebDataBinder binder) {  
	    binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));  
	}
	   
	/** 存放共享变量,或初始化操作 */
	@ModelAttribute
	public void init(ModelMap model) {}
	
	/** 列表 */
	@Login @RequestMapping
	public String index(ModelMap model,UserQuery query,HttpServletRequest request,HttpServletResponse response) {
		Page page = this.userManager.findPage(query);
//		List<User> rs=userManager.findAll();
//		for (User user : rs) {
//			System.out.println("userlist");
//			System.out.println(user.getName());
//			System.out.println(user.getPassword());
//			System.out.println(user.getUserId());
//			System.out.println(user.getRelatedId());
//		}
		model.addAllAttributes(toModelMap(page, query));
		return "/user/index";
	}
	
	/** 显示 */
	@Login @RequestMapping(value="/{id}")
	public String show(ModelMap model,@PathVariable java.lang.Integer id) throws Exception {
		User user = (User)userManager.getById(id);
		model.addAttribute("user",user);
		//添加学生或老师表的信息
		if(user.getType()==1){
			Teacher teacher = (Teacher)teacherManager.getById(user.getRelatedId());
			model.addAttribute("teacher",teacher);
		}else if(user.getType()==2){
			Student student = (Student)studentManager.getById(user.getRelatedId());
			model.addAttribute("student",student);
		}
		return "/user/show";
	}

	/** 进入新增 */
	@Login @RequestMapping(value="/{type}/new")
	public String _new(ModelMap model,@PathVariable java.lang.Integer type,StudentUser studentUser,TeacherUser teacherUser,HttpServletRequest request,HttpServletResponse response) throws Exception {
		if(type==1){
			model.addAttribute("user",teacherUser);
			return "/user/new1";
		}
		if(type==2){
			model.addAttribute("user",studentUser);
			return "/user/new";
		}
		return "/user/new";
	}
	
	/** 保存新增 */
	@Login @RequestMapping(value="/student",method=RequestMethod.POST)
	public String createStudentUser(ModelMap model,@Valid StudentUser user,BindingResult errors,HttpServletRequest request,HttpServletResponse response) throws Exception {
		Student studentInfo = new Student();
		User userInfo = new User();
		studentInfo.setStudentId(user.getStudentId());
		studentInfo.setStudentNumber(user.getStudentNumber());
		studentInfo.setSchool(user.getSchool());
		studentInfo.setDirection(user.getDirection());
		studentInfo.setEntranceClass(user.getEntranceClass());
		studentInfo.setMajor(user.getMajor());
		studentInfo.setMaxYear(user.getMaxYear());
		studentInfo.setMinYear(user.getMinYear());
		studentManager.save(studentInfo);
		userInfo.setRelatedId(studentInfo.getStudentId());
		userInfo.setBirth(user.getBirth());
		userInfo.setBorrowTypeId(user.getBorrowTypeId());
		userInfo.setCreateTime(user.getCreateTime());
		userInfo.setEmail(user.getEmail());
		userInfo.setGender(user.getGender());
		userInfo.setName(user.getName());
		userInfo.setPassword(user.getPassword());
		userInfo.setPhone(user.getPhone());
		userInfo.setState(user.getState());
		userInfo.setTel(user.getTel());
		userInfo.setUserName(user.getUserName());
		userInfo.setUserId(user.getUserId());
		userManager.save(userInfo);
		
		Flash.current().success(CREATED_SUCCESS); 
		return LIST_ACTION;
	}
	@Login @RequestMapping(value="/teacher",method=RequestMethod.POST)
	public String createTeacherUser(ModelMap model,@Valid TeacherUser user,BindingResult errors,HttpServletRequest request,HttpServletResponse response) throws Exception {
		User userInfo = new User();
		Teacher teacherInfo = new Teacher();
		teacherInfo.setDepartment(user.getDepartment());
		teacherInfo.setDirection(user.getDirection());
		teacherInfo.setOffice(user.getOffice());
		teacherInfo.setTeacherId(user.getTeacherId());
		teacherInfo.setTeacherNumber(user.getTeacherNumber());
		teacherInfo.setTitle(user.getTitle());
		teacherManager.save(teacherInfo);
		userInfo.setRelatedId(teacherInfo.getTeacherId());
		userInfo.setBirth(user.getBirth());
		userInfo.setBorrowTypeId(user.getBorrowTypeId());
		userInfo.setCreateTime(user.getCreateTime());
		userInfo.setEmail(user.getEmail());
		userInfo.setGender(user.getGender());
		userInfo.setName(user.getName());
		userInfo.setPassword(user.getPassword());
		userInfo.setPhone(user.getPhone());
		userInfo.setState(user.getState());
		userInfo.setTel(user.getTel());
		userInfo.setUserName(user.getUserName());
		userInfo.setUserId(user.getUserId());
		userManager.save(userInfo);
		Flash.current().success(CREATED_SUCCESS); 
		return LIST_ACTION;
	}
	
	/** 编辑 */
	@Login @RequestMapping(value="/{id}/edit")
	public String edit(ModelMap model,@PathVariable java.lang.Integer id) throws Exception {
		User user = (User)userManager.getById(id);
//		model.addAttribute("user",user);
		//添加学生或老师表的信息
		if(user.getType()==1){
			Teacher teacher = (Teacher)teacherManager.getById(user.getRelatedId());
			TeacherUser teacherUser = new TeacherUser();
			teacherUser.setBirth(user.getBirth());
			teacherUser.setBorrowTypeId(user.getBorrowTypeId());
			teacherUser.setCreateTime(user.getCreateTime());
			teacherUser.setDepartment(teacher.getDepartment());
			teacherUser.setDirection(teacherUser.getDirection());
			teacherUser.setEmail(user.getEmail());
			teacherUser.setGender(user.getGender());
			teacherUser.setName(user.getName());
			teacherUser.setOffice(teacher.getOffice());
			teacherUser.setPassword(user.getPassword());
			teacherUser.setPhone(user.getPhone());
			teacherUser.setState(user.getState());
			teacherUser.setTeacherId(teacher.getTeacherId());
			teacherUser.setTeacherNumber(teacher.getTeacherNumber());
			teacherUser.setTel(user.getTel());
			teacherUser.setTitle(teacher.getTitle());
			teacherUser.setType(user.getType());
			teacherUser.setUserId(user.getUserId());
			teacherUser.setUserName(user.getUserName());
			model.addAttribute("user",teacherUser);
		}else if(user.getType()==2){
			Student student = (Student)studentManager.getById(user.getRelatedId());
			StudentUser studentUser = new StudentUser();
			studentUser.setBirth(user.getBirth());
			studentUser.setBorrowTypeId(user.getBorrowTypeId());
			studentUser.setCreateTime(user.getCreateTime());
			studentUser.setEmail(user.getEmail());
			studentUser.setGender(user.getGender());
			studentUser.setName(user.getName());
			studentUser.setPassword(user.getPassword());
			studentUser.setPhone(user.getPhone());
			studentUser.setState(user.getState());
			studentUser.setTel(user.getTel());
			studentUser.setType(user.getType());
			studentUser.setUserId(user.getUserId());
			studentUser.setUserName(user.getUserName());
			studentUser.setStudentId(student.getStudentId());
			studentUser.setStudentNumber(student.getStudentNumber());
			studentUser.setMaxYear(student.getMaxYear());
			studentUser.setMinYear(student.getMinYear());
			studentUser.setMajor(student.getMajor());
			studentUser.setDirection(student.getDirection());
			studentUser.setSchool(student.getSchool());
			studentUser.setEntranceClass(student.getEntranceClass());
			model.addAttribute("user",studentUser);
		}
		return "/user/edit";
	}
	
	/** 保存更新 */
	@Login @RequestMapping(value="/{id}",method=RequestMethod.PUT)
	public String update(ModelMap model,@PathVariable java.lang.Integer id,@Valid User user,BindingResult errors,HttpServletRequest request,HttpServletResponse response) throws Exception {
		userManager.update(user);
		Flash.current().success(UPDATE_SUCCESS);
		return LIST_ACTION;
	}
	
	/** 删除 */
	@Login @RequestMapping(value="/{id}",method=RequestMethod.DELETE)
	public String delete(ModelMap model,@PathVariable java.lang.Integer id) {
		userManager.removeById(id);
		Flash.current().success(DELETE_SUCCESS);
		return LIST_ACTION;
	}

	/** 批量删除 */
	@Login @RequestMapping(method=RequestMethod.DELETE)
	public String batchDelete(ModelMap model,@RequestParam("items") java.lang.Integer[] items) {
		for(int i = 0; i < items.length; i++) {
			userManager.removeById(items[i]);
		}
		Flash.current().success(DELETE_SUCCESS);
		return LIST_ACTION;
	}	
	
	//改变用户状态
	@Login @RequestMapping(value="/{id}&{state}/changeState")
	public String changeState(@PathVariable Integer id,@PathVariable Integer state){
		Integer changeState = state;
		Integer userId = id;
		userManager.changeState("userId", userId, "state", changeState);
		return LIST_ACTION;
	} 
}

